#include "musicplayer.h"
#include "ui_musicplayer.h"


musicplayer::musicplayer(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::musicplayer)
{
    ui->setupUi(this);
    ui->widget_3->hide();
    m_time_1 = new QTimer;

//    m_time_1->setInterval(100);
//    m_time_1->setTimerType(Qt::PreciseTimer);

    words_flag = false;
    manager_2 = new QNetworkAccessManager(this);
    connect(manager_2, SIGNAL(finished(QNetworkReply*)),
            this, SLOT(replyFinished_2(QNetworkReply*)));
    ui->pushButton->setIcon(QPixmap(":/sousuo.png"));
    // 1.4 图标设定
    this->setWindowIcon(QIcon(":/toux.png"));
    this->setWindowTitle("音乐搜索");
       pModel = new QStandardItemModel(10,5,ui->tableView);
       QStringList list = QStringList()<<"歌名"<<"专辑"<<"歌手"<<"时长"<<"喜欢";
       pModel->setHorizontalHeaderLabels(list);//设置数据的表头
       ui->tableView->setModel(pModel);



       ui->tableView->setStyleSheet(
           "QTableView { " "    background: transparent; "
           "    gridline-color: transparent; "
           "}"
           "QHeaderView { "
           "    background: transparent; "
           "    border: none; "
           "}"
       );

      ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);

      ui->tableView->setStyleSheet(
          "background-image: url(':/img/jqm0.png');"
          "background-repeat: no-repeat;"
          "background-position: center;"
          "background-attachment: fixed;"
          "background-size: cover;" ); // 图片将覆盖整个窗口，可能会裁剪
      //表列随着表格变化而自适应变化
       ui->tableView->horizontalHeader()-> setSectionResizeMode(QHeaderView::Stretch);
       //表行随着表格变化而自适应变化
        ui->tableView->verticalHeader()-> setSectionResizeMode(QHeaderView::Stretch);
        ui->tableView->show();
        manager = new QNetworkAccessManager(this);
        connect(manager,SIGNAL(finished(QNetworkReply*)),
                this,SLOT(replyFinished(QNetworkReply*)));

        ui->tableView->horizontalHeader()->setStyleSheet("QHeaderView::section{background-color: transparent;};selection-background-color: rgb(77, 77, 77);");

        playlist = new QMediaPlaylist;//媒体播放列表
        player = new QMediaPlayer;//媒体播放器
        player->setPlaylist(playlist);
        connect(player,SIGNAL(positionChanged(qint64)),this,SLOT(positionChangedSlot(qint64)));

}

musicplayer::~musicplayer()
{
    delete ui;
   // delete m_time_1;
}



void musicplayer::replyFinished(QNetworkReply *reply)
{
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)==200)
    {
        qDebug()<<"服务器访问成功"<<endl;

       parseJson(reply->readAll());
    }
}

void musicplayer::parseJson(QByteArray byteArray)
{
    unsigned int id = 0;
    QString songName;
    QString albumName;
    QString singerName;
    QString songtime;
    QString duration;
 //   float duration = -1;
    musicIDList.clear();
    playlist->clear();

     QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
     if(doc.isObject())//询问文档内部是否是一个对象
     {
             qDebug()<<"该文档是一个对象"<<endl;
             QJsonObject obj1 = doc.object();//返回文档的对象
             if(obj1.contains("result")==false)//询问文档对象是否含result关键字
             {
                 qDebug()<<"错误的JSON对象"<<endl;
                 return;
             }
             QJsonValue var = obj1.value("result");//获得关键字result对应的结果
             if(var.isObject()==false)
             {
                 qDebug()<<"result的值不是对象"<<endl;
                 return;
             }
             QJsonObject resultObj = var.toObject();//把result的值转为对象
             if(resultObj .contains("songs")==false)
             {
                 qDebug()<<"JSON对象没有歌曲"<<endl;
                 return;
             }
              var = resultObj.value("songs");//得到关键字songs的值
             if(var.isArray())//询问是否为数组
             {
                 songsArry = var.toArray();//将songs的值转为一个数组
                 qDebug()<<"一共搜索到"<<songsArry.size()<<"首歌曲"<<endl;
                 for(int i = 0;i<songsArry.size();i++)
                 {
                     QJsonObject songsObj = songsArry[i].toObject();
                     if(songsObj.contains("id"))
                     {
                         QJsonValue varID = songsObj.value("id");//获取关键字为id的元素的值
                         id = varID.toDouble();//为了避免数组越界，使用double类型返回ID号
                     }
                     if(songsObj.contains("name"))
                     {
                         QJsonValue varName = songsObj.value("name");//获取关键字为name的元素的值
                         songName = varName.toString();
                     }

                     if(songsObj.contains("album"))//是否包含专辑
                                    {
                                        QJsonValue varAlbum = songsObj.value("album");//得到专辑关键字的值
                                        if(varAlbum.isObject())
                                        {
                                            QJsonObject albumObj = varAlbum.toObject();//把专辑的值转为对象
                                            if(albumObj.contains("name"))
                                            {
                                                QJsonValue varAlbumName =  albumObj.value("name");
                                                albumName = varAlbumName.toString();//得到专辑名
                                            }
                                        }
                                    }
                     if(songsObj.contains("artists"))//是否包含作者关键字
                                    {
                                        QJsonValue varArtists = songsObj.value("artists");
                                        if(varArtists.isArray())//作者的值是否为数组？
                                        {
                                           QJsonArray arrArtists = varArtists.toArray();
                                           for (int i = 0; i < arrArtists.size(); ++i) {//遍历作者数组
                                               if(arrArtists[i].isObject())
                                               {
                                                   QJsonObject artistsObj = arrArtists[i].toObject();
                                                   if(artistsObj.contains("name"))
                                                   {
                                                       QJsonValue varArtistsName = artistsObj.value("name");
                                                       singerName+= varArtistsName.toString();//把名字加入到字符串中
                                                       singerName+=" ";//中间留一个空格
                                                   }
                                               }
                                           }
                                        }
                                    }
                                    if(songsObj.contains("duration"))
                                                   {

                                                       QJsonValue varDuration = songsObj.value("duration");//获取关键字为duration的元素的值
                                                       int var_time = varDuration.toInt();
                                                       int min=var_time/1000/60;
                                                       int sec=var_time/100%60;
                                                       duration=QString("%0分:%1秒").arg(min).arg(sec);
                                                   }



                                                   qDebug()<<id<<" "<<songName<<" "<<albumName<<" "<<singerName<<" "<<duration<<endl;

                      musicIDList.push_back(id);

 playlist->addMedia(QUrl(QString("http://music.163.com/song/media/outer/url?id=%1.mp3").arg(id)));
                 //把解析出来的歌曲信息加入到QTableView的数据模型中
                QStandardItem *item = new QStandardItem(songName);//歌名
                pModel->setItem(i, 0, item);
                item->setForeground(QBrush(QColor(Qt::blue)));

                item = new QStandardItem(albumName);
                pModel->setItem(i, 1, item);
                item->setForeground(QBrush(QColor(Qt::blue)));

                item = new QStandardItem(singerName);
                pModel->setItem(i, 2, item);
                item->setForeground(QBrush(QColor(Qt::blue)));

                item = new QStandardItem(QString("%0").arg(duration));
                pModel->setItem(i, 3, item);
                item->setForeground(QBrush(QColor(Qt::blue)));

 ////                在指定单元格插入图片
                itemWithImage = new QStandardItem();
                QPixmap pixmap(":/img/6.png"); // 更改为你图片的路径
                itemWithImage->setData(QPixmap(pixmap), Qt::DecorationRole); // 将图片设置为装饰角色

                    pModel->setItem(i, 4, itemWithImage); // 在 (0, 0) 插入图片


                singerName = "";//清空歌手名
                 }
                  ui->tableView->setModel(pModel);
                 playlist->setCurrentIndex(0);
             }
     }
}

void musicplayer::parseJson_2(QByteArray byteArray)
{

    lines.clear();
    QString lyric = " ";
    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
    if(doc.isObject())
    {
        qDebug()<<"该文档是一个对象"<<endl;
        QJsonObject obj1 = doc.object();
        if(obj1.contains("lrc") == false)
        {
            qDebug()<<"错误的JSON对象"<<endl;
            return;
        }
        QJsonValue varlrc = obj1.value("lrc");
        if(varlrc.isObject())
        {
            QJsonObject lrcObj = varlrc.toObject();
            if(lrcObj.contains("lyric"))
            {
                QJsonValue varlyric = lrcObj.value("lyric");
                lyric = varlyric.toString();
            }
        }
        lines = lyric.split('\n');//以\n分隔存放
    }
//    QString lyricName;

//    QJsonDocument doc = QJsonDocument::fromJson(byteArray);//直接从字节数组中获得一个JSON文档
//    if(doc.isObject())//询问文档内部是否是一个对象
//    {
//        qDebug()<<"该文档是一个对象"<<endl;
//        QJsonObject obj1 = doc.object();//返回文档的对象
//        if(obj1.contains("lrc")==false)//询问文档对象是否含lrc关键字
//        {
//            qDebug()<<"错误的JSON对象"<<endl;
//            return;
//        }
//        QJsonValue var = obj1.value("lrc");//获得关键字lrc对应的结果
//        if(var.isObject()==false)
//        {
//            qDebug()<<"lrc的值不是对象"<<endl;
//            return;
//        }
//        QJsonObject lrcObj = var.toObject();//把lrc的值转为对象

//        if(lrcObj.contains("lyric"))
//        {
//            QJsonValue lyric = lrcObj.value("lyric");//获取关键字为lyric的元素的值
//            lyricName = lyric.toString();
//        }
//        qDebug()<<lyricName<<endl;
//    }

}

void musicplayer::on_pushButton_clicked()
{
    manager->get(QNetworkRequest(QUrl(QString("http://music.163.com/api/search/get/web?csrf_token=hlpretag=&hlposttag=&s=%1&type=1&offset=0&total=true&limit=10").arg(ui->lineEdit->text()))));
}

void musicplayer::on_tableView_doubleClicked(const QModelIndex &index)
{
//    qDebug()<<index<<endl;

//     playlist->setCurrentIndex(index.row());
//     player->play();
  //  emit mp4is();
        playlist->setCurrentIndex(index.row());
       player->play();
       m_time_1->start();

       int play_index = index.row();

       manager_2->get(QNetworkRequest(QUrl(QString("http://music.163.com/api/song/lyric?id=%1&lv=1&kv=1&tv=-1").arg(musicIDList[play_index]))));
       qDebug()<<musicIDList[play_index]<<endl;

}

void musicplayer::replyFinished_2(QNetworkReply *reply)
{
    if(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute)==200)
    {
        qDebug()<<"获取歌词"<<endl;

       parseJson_2(reply->readAll());
    }
}

void musicplayer::on_pushButton_2_clicked()
{
    if(words_flag == false)
    {
        ui->widget_3->show();
    }
    else
    {
        ui->widget_3->hide();
    }
    words_flag = !words_flag;
}

void musicplayer::positionChangedSlot(qint64 position)
{
    int totalSeconds2 = position / 1000; // 转换为秒
    int minutes2 = totalSeconds2 / 60;
    int seconds2 = totalSeconds2 % 60;
    QString currentTimeLabel2 = QString("%1:%2").arg(minutes2, 2, 10, QChar('0')).arg(seconds2, 2, 10, QChar('0'));

    if(lines.isEmpty())
         {
             ui->label->setText("此歌曲为没有填词的纯音乐, 请您欣赏");
         }
         else
         {
             QString linelyric;//每行歌词
             // 遍历lines的结点，并截取存入linelyric，即动态显示每一行歌词
             for (const QString &line : lines) {
                 // 查找并提取括号内的数字
                 QString timestamp = line.mid(1, 5);
                 for (int i = 0; i < line.size(); i++) {
                     if(line[i] == ']')
                     {
                         linelyric = line.mid(i+1);
                     }
                 }
                 // 比较两个时间
                 if (timestamp == currentTimeLabel2) {
                     ui->label->setText(linelyric);
                 }
             }
         }
}















